import React, {useEffect, useState} from 'react'
import {Form, Button, DatePicker, Input, Modal, Radio, Select, Steps, Row, Col, TreeSelect, message, Upload} from 'antd'
import {UploadOutlined} from '@ant-design/icons';
import {dimissionTypeList, modeList, evaluationList, socialTraineeStateArray, reinstateList, employeeStatusList} from '@/utils/constant'
import {getResignationId} from '../../service'
import moment from 'moment'
import {connect} from 'umi'
import {getUploadUrl} from "@/utils/upload";

const FormItem = Form.Item;
const {TextArea} = Input;

const formLayout = {
  labelCol: {span: 7},
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const CreateForm = (props) => {
  const {visible, onSubmit, onCancel, current, personnel = {}, currentUser = {}} = props;
  const {options = {}} = personnel;
  const { jobLevel = [] } = options;
  const [form] = Form.useForm();
  const [fileName, setFileName] = useState(null);
  const [fileUploadUrls, setFileUploadUrls] = useState([]);
  const [fileList, setFileList] = useState([]);

  const fileProps = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    fileList: fileList,
    beforeUpload(file) {
      if (file.size/1024 > 10000) {
        message.error(`上传文件大小不能超过10M！`);
        return false;
      }
      setFileName(file.name)
    },
    onChange(info) {
      const {status} = info.file;
      if (status === 'done') {
        if (info.file.response.error) {
          message.success(`${info.file.response.error} 。`);
        } else {
          let urls = fileUploadUrls;
          urls.push(info.file.response);
          setFileUploadUrls(urls);
          message.success(`${info.file.name} 文件上传成功。`);
        }
      } else if (status === 'error') {
        message.error(`${info.file.name} 文件上传失败。`);
      }
      let files = info.fileList.filter(item => item.status);
      setFileList(files);
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  useEffect(()=>{
    if (current){
      current.jobLevel = current.jobLevelId ? jobLevel.find(item => item.id===current.jobLevelId)?.name : '';
      current.applyTime = moment();
      current.applyCode = currentUser.usercode;
      current.applyDepartment = currentUser.department;
      current.applyName = currentUser.name;
      if (current.fileUrlList.length>0){
        setFileUploadUrls(current.fileUrlList);
        current.fileUrlList.forEach((item,index) =>{
          uploadedFiles.push({
            uid: index,
            name: item.split('----')[1],
            status: 'done',
            url: item,
          })
        })
      }
      form.setFieldsValue(current);
    }
  },[current]);

  const onFormCancel = () => {
    setFileUploadUrls([]);
    uploadedFiles = [];
    form.resetFields();
    onCancel();
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    onSubmit({...current, ...fieldsValue, urlIdsList: fileUploadUrls});
    setFileUploadUrls([]);
    uploadedFiles = [];
  };

  const renderContent = () => {
      return (
        <>
          <Row gutter={24}>
            <Col {...colStyle}>
              <FormItem name="applyName" label="申请人">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="applyTime" label="申请日期">
                <DatePicker disabled={true} className='widthStyle'/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="applyDepartment" label="申请人部门">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="code" label="工号">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="name" label="姓名">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="idcard" label="身份证">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="mobile" label="电话">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="orgname" label="公司名称">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="unitname" label="部门名称">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="jobname" label="岗位">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="jobLevel" label="职级">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="hiredate" label="入职日期">
                <DatePicker disabled={true} className='widthStyle'/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="workingYears" label="司龄">
                <Input disabled={true}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="dimissionTime" label="离职日期">
                <DatePicker disabled={true} className='widthStyle'/>
              </FormItem>
            </Col>

            <Col span={24}>
              <FormItem name="remark" labelCol={{span: 2}} label="离职原因">
                <TextArea rows={8} className='widthStyle'/>
              </FormItem>
            </Col>
            <Col span={24}>
              <Upload {...fileProps}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </Col>
          </Row>
        </>
      )
  };

  const renderFooter = () => {
      return (
        <>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="结算信息填写"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{paddingTop: '24px'}}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user,personnel}) => ({
  personnel,
  currentUser: user.currentUser,
}))(CreateForm)
